<template>
  <div id="Booking-management">
      <div class="address">
        <h3>预订管理</h3>
      </div>
      <div class="show-Room"> 
        <el-scrollbar style="height: 100%;"> <!-- 滚动条 -->
          <el-table
            class="room-type-table TABLEMINWIDH"
            ref="multipleTable"
            :data="bookOrders"
            :key="updateTableKey"
            tooltip-effect="dark"
            style="width: 100%;font-size: 1.5rem;">
            <!-- 选择框 -->
            <el-table-column
              type="selection"
              min-width="10%">
            </el-table-column>
            <!-- 订单号 -->
            <el-table-column
              label="订单号"
              prop="obin"
              header-align="center"
              align="center"
              min-width="10%">
            </el-table-column>
            <!-- 房型 -->
            <el-table-column
              label="房型"
              prop="roomTypeTitle"
              header-align="center"
              align="center"
              class="test"
              min-width="10%">
            </el-table-column>
            <!-- 预订人 -->
            <el-table-column
              label="预订人"
              header-align="center"
              align="center"
              min-width="25%">
              <template slot-scope="scope">
                <p><span class="roomerName">{{scope.row.roomerName}}</span> : <span class="roomerPhone">{{scope.row.roomerPhone}}</span></p>
                <span class="roomerID">{{scope.row.roomerID}}</span>
              </template>
            </el-table-column>
            <!-- 预订时间 -->
            <el-table-column
              label="预订时间"
              header-align="center"
              align="center"
              min-width="25%">
              <template slot-scope="scope">
                <p><span>from : {{timeFormatter(scope.row.checkInTime)}}</span></p>
                <p><span>to : {{timeFormatter(scope.row.checkOutTime)}}</span></p>
              </template>
            </el-table-column>
            <!-- 状态 -->
            <el-table-column
              label="状态"
              header-align="center"
              align="center"
              min-width="10%"
              show-overflow-tooltip>
              <template slot-scope="scope">
                <span :style="{color:bookOrderStatusColor[scope.row.bsin]}">{{bookOrderStatus[scope.row.bsin]}}</span>
              </template>
            </el-table-column>
            <!-- 操作 -->
            <el-table-column
              prop="description"
              header-align="center"
              align="center"
              min-width="15%">
              <template slot-scope="scope">
                <div v-if="scope.row.bsin === 3">
                  <el-button size="small" @click="toCheckIn(scope.row)" type="primary">办理入住</el-button>
                  <el-button size="small" @click="cancleCheckIn(scope.row)" type="danger">取消入住</el-button>
                </div>
                <div v-else-if="scope.row.bsin === 0 || scope.row.bsin === 1 || scope.row.bsin === 4">
                </div>
                <div v-else>
                  <el-button size="small" @click="toConfirm(scope.row)" type="primary">确认入住</el-button>
                  <el-button size="small" @click="rejectCheckIn(scope.row)" type="danger">拒绝入住</el-button>
                </div>
              </template>
            </el-table-column>
          </el-table>
        </el-scrollbar><!-- /滚动条 -->
      </div>
      <el-dialog title='入住订单' :visible.sync="dialogTableVisible" :close-on-click-modal="false">
        <el-form ref="form" :model="form" label-width="80px">
          <el-form-item label="订单号">
            暂无
          </el-form-item>
          <el-form-item label="入住时间" class="checkInTime">
            <span>{{form.checkInTime}}</span>
          </el-form-item>
          <el-form-item label="离开时间" class="checkInTime">
            <span>{{form.checkOutTime}}</span>
          </el-form-item>
          <el-form-item label="房间">
            <div>
              <span v-if="isShowSummitButton">{{form.roomTypeTitle}} / {{form.roomPlate}}</span>
              <div v-else>
                <!-- <div class="block">
                  <el-cascader
                    v-model="newPlateValue"
                    :options="options">
                  </el-cascader>
                </div> -->
                {{form.roomTypeTitle}} / 
                 <el-select v-model="newPlateValue" placeholder="请选择">
                  <el-option
                    v-for="item in options"
                    :key="item.value"
                    :label="item.label"
                    :value="item.value">
                  </el-option>
                </el-select>
              </div>
            </div>
          </el-form-item>
          <el-form-item label="vip卡号">
            <span>{{form.vip}}</span>
          </el-form-item>
          <el-form-item label="预订单">
            <span v-if="!form.obin">无</span>
            {{form.obin}}
          </el-form-item>
          <el-form-item label="入住状态">
            <span>已入住</span>
          </el-form-item>
          <el-form-item label="价格" v-if="form.roomPrice">
            {{form.roomPrice}}
            <span style="color:red">* {{discount[form.vipLevel]}}</span> 
          </el-form-item>
          <el-form-item label="总价" v-if="form.roomPrice" style="color:red">
            {{form.finalPrice}}
          </el-form-item>
           <el-form-item label="顾客" v-for="cust in customers" :key="cust.id">
            <div v-if="isShowSummitButton">
              <span class="customer-text">名字 : {{cust.roomerName}}</span>
              <span class="customer-text">身份证 :  {{cust.roomerID}}</span> 
            </div>
            <div v-else> 
              <span class="customer-text1">名字 :</span> <el-input class="customer" v-model="cust.roomerName"></el-input><br>
              <span class="customer-text1">身份证 :</span> <el-input class="customer" v-model="cust.roomerID" style="margin-top: 20px;"></el-input>
            </div>
          </el-form-item>
           <el-form-item class="btMeter" v-if="!isShowSummitButton">
            <div >
              <el-button @click="addCustomer"><i class="el-icon-plus"></i></el-button>
              <span class="block"></span>
            </div>
          </el-form-item>
          <el-form-item label="订单时间" v-if="form.orderTime">
            {{form.orderTime}}
          </el-form-item>
          <el-form-item class="btMeter">
            <div v-if="isShowSummitButton">
              <el-button @click="summitOrder">提交订单</el-button>
              <span class="block"></span>
            </div>
            <div v-else>
               <el-button @click="createCheckInOrder">生成订单</el-button>
               <span class="block"></span>
            </div>
          </el-form-item>
        </el-form>
      </el-dialog>
  </div>
</template>

<script>
import { timeFormatter, timeFormatter2 } from '@/utils/utils'
import { roomTypeMixin } from '@/utils/mixins/roomType'
import { loadingMixin } from '@/utils/mixins/loading'
import { getAllBookOrder, getAllCheckInOrder, getOneVip, addOneCustomerInBookOrder, addOneCheckInOrder, modifyOneBookOrder, getAllUnuseRoom } from '@/api/api'
import { showMessage } from '@/utils/utils'
export default {
  mixins: [ loadingMixin, roomTypeMixin ],
  name: 'Booking-management',
  data() {
    return {
      dialogTableVisible: false,
      isShowSummitButton:false,
      updateTableKey:Math.random(),
      discount: [1, 0.98, 0.95, 0.9, 0.88, 0.8, 0.75],

      bookOrders: [],
      bookOrderStatus: ['已拒绝', '已完成', '待确认', '已确认', '已取消'],
      bookOrderStatusColor: ['#F56C6C', '#F56C6C', '#409EFF', '#409EFF', '#F56C6C'],

      form: {
        "orderTime": null,
        "checkInTime":"",
        "checkOutTime":"",
        "roomTypeTitle":"",
        "roomPlate":"",
        "roomPrice":0,
        "vipLevel":0,
        "discount":1,
        "finalPrice": 0,
        "obin":null,
        "ocin":null,
        "csin":1,
        "vip":1 
      },

      newPlateValue:'',

      options:[],
      // roomType: [],

      // bug临时添加
      editingRow:'',

      customers: [],

      checkInOrder:[],
    }
  },
  methods: {
    timeFormatter,
    addCustomer() {
      this.customers.push({ roomerName: '', roomerID: '', ocin: -1})
    },
    //提交订单
    async summitOrder() {
      let obj = Object.assign({},this.form)
      obj.vip *= 1
      let time = timeFormatter2(new Date(),"yyyy-MM-dd hh:mm:ss")
      obj.orderTime = time.slice(0, 10) + "T" + time.slice(11) + '.000+0000'
      await Promise.resolve(addOneCheckInOrder(obj).then(response => {
          if(response.data === '添加成功!') {
            showMessage(this, '保存成功', 'success')
            this.isShowSummitButton = false
            this.dialogTableVisible = false
          }
        }).catch(error =>  showMessage(this, '入住订单添加失败！', 'error'))
      )

      // 修改预订订单
      this.modifyBookOrder(this.editingRow, 1)

      await Promise.resolve(getAllCheckInOrder().then(response => {
          this.checkInOrder = response.data.reverse()
          this.dialogTableVisible = false
        }).catch(error =>  showMessage(this, '获取所有入住订单失败！', 'error'))
      ) 

      if(this.checkInOrder.length === 0) console.log("null")
      let maxOcin = 0
      for(let o of this.checkInOrder) {
        if(maxOcin < o.ocin) maxOcin = o.ocin
      }
      for(let o of this.customers) {
        o['ocin'] = maxOcin 
        await  Promise.resolve(
          addOneCustomerInBookOrder().catch(error =>  showMessage(this, '房客记录添加失败！', 'error'))
        )
      }
    },
    // 生成订单
    createCheckInOrder() {
      this.form.roomPlate = this.newPlateValue
      this.isShowSummitButton = true
    },  
    // 办理入住
    async toCheckIn(row) {
      this.dialogTableVisible = true
      this.editingRow = row
      this.customers = []
      this.customers.push({ roomerName: row.roomerName, roomerID: row.roomerID, ocin: -1})
      // 预订订单转化为入住订单
      this.form.checkInTime = row.checkInTime
      this.form.checkOutTime = row.checkOutTime
      this.form.roomTypeTitle = row.roomTypeTitle
      this.form.obin = row.obin
      this.form.vip = row.roomerPhone
      for(let i in this.roomTypes) {
        if(this.roomTypes[i].title === this.form.roomTypeTitle) {
          this.form.roomPrice = this.roomTypes[i].price
        }
      }

      await Promise.resolve(getOneVip(row.roomerPhone).then(response => {
          if(response.data) {
            this.form.vipLevel = response.data.lv
            this.form.discount = this.discount[this.form.vipLevel]
            this.form.finalPrice = this.form.roomPrice * this.form.discount
          } else { //vip没有
            this.form.vipLevel = 0
            this.form.discount = 1
          }
        }).catch(error =>  showMessage(this, '获取一个vip失败！', 'error'))
      ) 

      await Promise.resolve(getAllUnuseRoom().then(response => {
          // 返回的数组从1开始
          response.data.splice(0, 1)
          if(response.data) {
            let Tin = -1
            for(let obj of this.roomTypes) {
              if(obj.title === this.form.roomTypeTitle) Tin = obj.tin
            }
            for(let obj of response.data) {
              if(obj.length > 0) {
                if(obj[0].tin === Tin) {
                  for(let obj2 of obj) {
                    this.options.push({value:obj2.rin,label:obj2.rin})
                  }
                  break
                }
              }
            }
          }
        }).catch(error =>  showMessage(this, '获取所有未使用房间失败！', 'error'))
      )
    },
    // 取消入住
    cancleCheckIn(row) {
      this.modifyBookOrder(row, 4)
    },
    // 待确认
    toConfirm(row) {
      this.modifyBookOrder(row ,3)
    },
    // 拒绝入住
    rejectCheckIn(row) {
      this.modifyBookOrder(row, 0)
    },
    // 修改一条预订单 ？
    modifyBookOrder(row, lastBsin) {
      modifyOneBookOrder(row.obin,{...row, "bsin":lastBsin}).then(response => {
        if(response.data === "修改成功！") {
          showMessage(this, '修改成功', 'success')
          row.bsin = lastBsin
          this.editingRow = ''
        }
      }).catch(error => showMessage(this, '预订单修改失败！', 'error'))
    },
    // 加载数据
    async load() {
      await this.updateRoomType()
      await Promise.resolve(getAllBookOrder().then(response => {
          this.bookOrders = response.data.reverse()
        }).catch(error =>  showMessage(this, '获取所有预订单失败！', 'error'))
      )
    },
  },
}
</script>

<style lang="less" scoped>
.address{
  position: relative;
  color: #aa97b0;
  top: -20px;
}
.customer{
  width: 400px;
}
.customer-text{
  display: inline-block;
  width: 230px;
}
.customer-text1{
  display: inline-block;
  width: 50px;
}
.roomerName{
  color: gold;
}
.roomerID{
  color: #ccc;
}
.roomerPhone{
  color: rgb(0, 255, 242);
}
.btMeter{
  display: flex;
  justify-content: center;
  align-items: center;
  .block{
    display: inline-block;
    width: 78px;
  }
}
</style>